<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col :md="4" :sm="8">
            <a-form-item label="车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNo"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="支付类型">
              <a-select @change="payTypeChange" defaultValue="">
                <a-select-option value="">选择支付类型</a-select-option>
                <a-select-option :value="1">微信</a-select-option>
                <a-select-option :value="2">支付宝</a-select-option>
                <a-select-option :value="3">无感支付</a-select-option>
                <a-select-option :value="4">全免劵</a-select-option>
                <a-select-option :value="5">储值卡</a-select-option>
                <a-select-option :value="6">线下收费</a-select-option>
              </a-select>

            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item>
              <a-select defaultValue="" @change="handleChangeSelect"> //1未支付，2支付成功，3支付失败
                <a-select-option value="">选择订单状态</a-select-option>
                <a-select-option value="1">未支付</a-select-option>
                <a-select-option value="2">支付成功</a-select-option>
                <a-select-option value="3">支付失败</a-select-option>

              </a-select>
            </a-form-item>
          </a-col>


          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="开始日期" @change="onChangeStartTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="结束日期" @change="onChangeEndTime"/>
            </a-form-item>

          </a-col>

          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <!-- <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button> -->

            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
        

        <span slot="action" slot-scope="text, record" v-has="'admin:parkCode'">
          <a @click="handleEdit(record)">详情</a>

        </span>

    </a-table>

    <parkOrderInfo-modal ref="modalForm" @ok="modalFormOk"></parkOrderInfo-modal>
  </a-card>
</template>

<script>
import ParkOrderInfoModal from './modules/ParkOrderInfoModal'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, downFile} from '@/api/manage'
import {filterObj} from '@/utils/util';
import {USER_AUTH, SYS_BUTTON_AUTH} from "@/store/mutation-types"
import parkInfoList from "@/components/parkInfoList";

export default {
  name: "ParkOrderInfoList",
  mixins: [JeecgListMixin],
  components: {
    ParkOrderInfoModal,parkInfoList
  },
  data() {
    return {
      description: '停车订单详情管理管理页面',
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '车牌号',
          align: "center",
          dataIndex: 'plateNo',
          width: 90,
        },
        {
          title: '停车场名称',
          align: "center",
          dataIndex: 'parkName',
          width: 150,
        },
        {
          title: '当前的停车费用(元)',
          align: "center",
          dataIndex: 'chargeUnpaid',
          width: 140,
          customRender: function (t, r, index) {
            return (t / 100).toFixed(2);
          }
        },
        {
          title: '已支付费用(元)',
          align: "center",
          dataIndex: 'chargePaid',
          width: 120,
          customRender: function (t, r, index) {
            return (t / 100).toFixed(2);
          }
        },
        {
          title: '入场时间',
          align: "center",
          dataIndex: 'enterTime',
          width: 150
        },
        {
          title: '出场时间',
          align: "center",
          dataIndex: 'outTime',
          width: 150
        },
        {
          title: '停车时长',
          align: "center",
          dataIndex: 'chargeDuration',
          width: 90,
          customRender: function (t, r, index) {
            var day = parseInt(t / 60 / 24);
            var hour = parseInt(t / 60 % 24);
            var min = parseInt(t % 60);
            t = "";
            if (day > 0) {
              t = day + "天";
            }
            if (hour > 0) {
              t += hour + "小时";
            }
            if (min > 0) {
              t += parseFloat(min) + "分钟";
            }

            return t == "" ? "0分钟" : t;
          }
        },

        {
          title: '预付费用(元)',
          align: "center",
          dataIndex: 'chargePrepaid',
          width: 100,
          customRender: function (t, r, index) {
            return (t / 100).toFixed(2);
          }
        },
        {
          title: '总优惠金额(元)',
          align: "center",
          dataIndex: 'couponAmt',
          width: 120,
          customRender: function (t, r, index) {
            return (t / 100).toFixed(2);
          }
        },

        {
          title: '总费用(元)',
          align: "center",
          dataIndex: 'chargeTotalFee',
          width: 100,
          customRender: function (t, r, index) {
            return (t / 100).toFixed(2);
          }
        },

        {
          title: '订单状态',
          align: "center",
          dataIndex: 'orderStatus',
          width: 80,
          customRender: function (t, r, index) {
            if (t == 1) {
              return "未支付";
            }
            if (t == 2) {
              return "支付成功";

              if (t == 3) {
                return "支付失败";
              }
            }
          }
        },

        {
          title: '支付类型',
          align: "center",
          dataIndex: 'payType',
          width: 80,
          customRender: function (t, r, index) {
            if (t == 1) {
              return "微信";
            } else if (t == 2) {
              return "支付宝";
            } else if (t == 3) {
              return "无感支付";
            } else if (t == 4) {
              return "全免劵";
            } else if (t == 5) {
              return "储值卡";
            } else if (t == 6) {
              return "线下收费";
            }
          }
        },

        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime'
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        list: "/order/parkOrderInfo/list",
        delete: "/order/parkOrderInfo/delete",
        deleteBatch: "/order/parkOrderInfo/deleteBatch",
        exportXlsUrl: "order/parkOrderInfo/exportXls",
        importExcelUrl: "order/parkOrderInfo/importExcel",
      },
      queryParam: {
        "createTime_begin": "",
        "createTime_end": "",

      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {
    this.keyupEnter();
    if (!this.hasPermission('admin:parkCode')) {
      this.columns.pop();
    }
  },
  methods: {
    parkInfoListChange(parkCode) {
      this.queryParam.parkCode = parkCode;
    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = false
    },
    hasPermission(permissionStr) {
      var permissionList = [];
      var allPermissionList = [];

      //let authList = Vue.ls.get(USER_AUTH);
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]");
      for (var auth of authList) {
        if (auth.type != '2') {
          permissionList.push(auth);
        }
      }
      //console.log("页面权限--Global--",sessionStorage.getItem(SYS_BUTTON_AUTH));
      let allAuthList = JSON.parse(sessionStorage.getItem(SYS_BUTTON_AUTH) || "[]");
      for (var gauth of allAuthList) {
        if (gauth.type != '2') {
          allPermissionList.push(gauth);
        }
      }
      //设置全局配置是否有命中
      var invalidFlag = false;//无效命中
      if (allPermissionList != null && allPermissionList != "" && allPermissionList != undefined && allPermissionList.length > 0) {
        for (var itemG of allPermissionList) {
          if (permissionStr === itemG.action) {
            if (itemG.status == '0') {
              invalidFlag = true;
              break;
            }
          }
        }
      }
      if (invalidFlag) {
        return true;
      }
      if (permissionList === null || permissionList === "" || permissionList === undefined || permissionList.length <= 0) {
        return false;
      }
      let permissions = [];
      for (var item of permissionList) {
        if (item.type != '2') {
          permissions.push(item.action);
        }
      }
      return permissions.includes(permissionStr);
    },
    payTypeChange(value) {
      this.queryParam.payType = `${value}`
    },

    handleChangeSelect(value) {
      this.queryParam.orderStatus = `${value}`
    },
    handleExportXls(fileName) {

      let startTime = this.queryParam.createTime_begin;
      let endTime = this.queryParam.createTime_end;
      let opDesc = this.queryParam.opDesc;
      let dayTime = startTime;
      if (startTime == "") {
        this.$message.error("请选择导出开始日期");
        return
      }
      if (endTime == "") {
        this.$message.error("请选择导出结束日期");
        return
      }
      if (startTime != "" && endTime != "") {
        if (startTime != endTime) {
          this.$message.error("仅支持1天数据导出,请选择导出日期");
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }


      this.queryParam.dayTime = dayTime;
      fileName = dayTime + fileName;
      let param = {...this.queryParam};
      if (this.queryParam.createTime_begin != "" && this.queryParam.createTime_end != "") {
        param.createTime_begin = this.queryParam.createTime_begin + " 00:00:00";
        param.createTime_end = this.queryParam.createTime_end + " 23:59:59";
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },


    onChangeStartTime(date, dateString) {
      this.queryParam.createTime_begin = dateString;
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.createTime_end = dateString;
    },


    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },

    searchQuery() {
      let startTime = this.queryParam.createTime_begin;
      let endTime = this.queryParam.createTime_end;

      if (startTime != "" && endTime != "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }

      this.loadData(1);
    },

    getQueryParams() {

      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.createTime_begin != "" && this.queryParam.createTime_end != "") {
        param.createTime_begin = this.queryParam.createTime_begin + " 00:00:00";
        param.createTime_end = this.queryParam.createTime_end + " 23:59:59";
      }

      // delete param.createTimeRange; // 时间参数不传递后台
      return filterObj(param);
    },

    batchDel: function () {

      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].invateuserdetailId + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }
    },
    handleDelete: function (invateuserdetailId) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {invateuserdetailId: invateuserdetailId}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },


    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1);
        }
      }
    },

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>